class Compiler {
    constructor (vm) {
        this.el = vm.$el
        this.vm = vm
        this.compiler(this.el)
      }
  // 编译模版,处理文本节点和元素节点
  compiler (el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) { // 是否是文本节点
        this.compileText(node)
      } else {
        if (this.isElementNode(node)) {
          this.compileElement(node)
        }
      }
      // 判断node是否有子节点
      if (node.childNodes && node.childNodes.length) {
        this.compiler(node)
      }
    })
  }
  // 编译文本节点,处理差值表达式
  compileText (node) {
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue
      })
    }
  }
  // 编译元素节点,处理v-指令
  compileElement (node) {
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name
      if (this.isDirective(attr.name)) {
        attrName = attrName.substr(2)
        let key = attr.value
        if (attrName.startsWith('on')) {
          const event = attrName.split(':')[1]
          return this.eventUpdate(node, key, event)
        }
        this.update(node, key, attrName)
      }
    })
  }
  eventUpdate (node, key, event) {
    this.onUpdater(node, key, event)
  }
  update (node, key, attrName) {
    let updataFn = this[attrName + 'Updater']
    updataFn && updataFn.call(this, node, this.vm[key], key)
  }
  // 处理v-text指令
  textUpdater (node, value, key) {
    node.textContent = value
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue
    })
  }
  // 处理v-model指令
  modelUpdater (node, value, key, attrName) {
    node.value = value
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue
    })
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }
  // 处理v-html指令
  htmlUpdater (node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, (newValue) => {
      node.innerHTML = newValue
    })
  }
  // 处理v-on指令
  onUpdater (node, key, event) {
    node.addEventListener(event, (e) => this.vm[key](e))
  }
  // 判断元素属性是否是指令
  isDirective (attrName) {
    return attrName.startsWith('v-')
  }
  // 判断节点是否是文本节点
  isTextNode (node) {
    return node.nodeType === 3
  }
  // 判断节点是否是元素节点
  isElementNode (node) {
    return node.nodeType === 1
  }
}